package proxy

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"strconv"
	"strings"
)

type HttpProxy struct {
	client *http.Client
	Host string
	Port int
}

func NewHttpProxy(targetServer string) *HttpProxy {
	host := "localhost"
	port := 8080
	if len(targetServer) > 0 && strings.Contains(targetServer, ":") {
		arr := strings.Split(targetServer, ":")
		host = arr[0]
		port, _ = strconv.Atoi(arr[1])
	}

	return &HttpProxy{
		client: http.DefaultClient,
		Host: host,
		Port: port,
	}
}

func (p *HttpProxy) HttpForward(request *http.Request) (*http.Response, error) {
	targetUrl := fmt.Sprintf("http://%s:%d%s", p.Host, p.Port, request.RequestURI)

	data, err := io.ReadAll(request.Body)
	if err != nil {
		log.Println("read request error, " + err.Error())
		return nil, err
	}
	defer request.Body.Close()

	forwardRequest, err := http.NewRequest(request.Method, targetUrl, bytes.NewBuffer(data))
	if err != nil {
		return nil, err 
	}
	for key, value := range request.Header {
		forwardRequest.Header.Add(key, value[0])
	}

	response, err := p.client.Do(forwardRequest)
	if err != nil {
		return nil, err 
	}
	return response, nil 
}